import 'package:wu_you/utils/logger_util.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static const TABLE_SEARCH_HISTORY = "CREATE TABLE search_history("
      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
      "mobile TEXT, "
      "search_content TEXT, "
      "search_count INTEGER"
      ")";

  static const IDX_TABLE_SEARCH_HISTORY =
      "CREATE UNIQUE INDEX index_search_content on search_history (search_content)";


  static const TABLE_TRANSFER_USER = "CREATE TABLE transfer_user("
      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
      "mobile TEXT, "
      "user_name TEXT, "
      "transfer_count INTEGER"
      ")";

  static const IDX_TABLE_TRANSFER_USER =
      "CREATE UNIQUE INDEX index_user_name on transfer_user (user_name)";




  static const TABLE_LOGIN_USER = "CREATE TABLE login_history("
      "id INTEGER PRIMARY KEY AUTOINCREMENT, "
      "user_name TEXT, "
      "pass_word TEXT, "
      "login_count INTEGER"
      ")";

  static const IDX_TABLE_LOGIN_USER =
      "CREATE UNIQUE INDEX login_user_name on login_history (user_name)";



  factory DatabaseHelper() => _getInstance();
  static DatabaseHelper _instance;

  DatabaseHelper._internal();

  static DatabaseHelper _getInstance() {
    if (_instance == null) {
      _instance = DatabaseHelper._internal();
    }
    return _instance;
  }

  static const int _DB_VERSION = 1;

  Database _db;

  Future<Database> db() async {
    if (_db == null) {
      String path = join(await getDatabasesPath(), 'jj_database.db');
      _db = await openDatabase(path,
          version: _DB_VERSION, onCreate: _onCreate, onUpgrade: _onUpgrade);
    }
    return _db;
  }

  void _onCreate(Database db, int newVersion) async {
    await db.execute(TABLE_SEARCH_HISTORY);
    await db.execute(IDX_TABLE_SEARCH_HISTORY);
    await db.execute(TABLE_TRANSFER_USER);
    await db.execute(IDX_TABLE_TRANSFER_USER);
    await db.execute(TABLE_LOGIN_USER);
    await db.execute(IDX_TABLE_LOGIN_USER);
  }

  void _onUpgrade(Database db, int oldVersion, int newVersion) async {
    LoggerUtil.d("_onUpgrade: oldVersion = $oldVersion, newVersion = $newVersion");
  }
}
